﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace ViazyNetCore
{
    public class CurrentUser : ICurrentUser
    {
        private static readonly Claim[] EmptyClaimsArray = [];

        public virtual long Id => _principalAccessor.Principal?.GetUserId() ?? 0;

        public virtual bool IsAuthenticated => Id != 0;

        public virtual string Username => this.FindClaimValue(JwtClaimTypes.Name);

        public virtual string Nickname => this.FindClaimValue(JwtClaimTypes.NickName);

        public virtual string PhoneNumber => this.FindClaimValue(JwtClaimTypes.PhoneNumber);

        public virtual string[] Roles => FindClaims(JwtClaimTypes.Role).Select(c => c.Value).Distinct().ToArray();

        public virtual AuthUserType IdentityType => this.FindClaimValue<AuthUserType>(JwtClaimTypes.Type);

        public virtual bool IsModerated => false;

        public virtual long TenantId => _principalAccessor.Principal?.FindTenantId() ?? 0;


        private readonly ICurrentPrincipalAccessor _principalAccessor;

        public CurrentUser(ICurrentPrincipalAccessor principalAccessor)
        {
            _principalAccessor = principalAccessor;
        }

        public virtual Claim? FindClaim(string claimType)
        {
            return _principalAccessor.Principal?.Claims.FirstOrDefault(c => c.Type == claimType);
        }

        public virtual Claim[] FindClaims(string claimType)
        {
            return _principalAccessor.Principal?.Claims.Where(c => c.Type == claimType).ToArray() ?? EmptyClaimsArray;
        }

        public virtual Claim[] GetAllClaims()
        {
            return _principalAccessor.Principal?.Claims.ToArray() ?? EmptyClaimsArray;
        }
    }
}
